<?php
class UsersController extends AppController{

    var $name='Users';
    var $uses = array("Attachment","User","Group","CompPerson","CompFinacerelease","CompJobapply",'SearchCompany','Company','Codetype','Constant','ProCvalue','Colleage','CgPerson','Notice');
    var $helpers=array('Pagination','Html','Javascript','Form','Fck','Str','Action','Accp');
    var $components = array ('Pagination','Session','Cookie');
    var $layout='hindex';
    
    function login(){
     	
        $notices = $this->Notice->findAll('Notice.is_deleted = 0', '', $order = null, 5, '', '');
        
        $this->set(compact('notices'));

        $this->layout = "loginindex";
        $autologin = $this->Cookie->read("autologin");
        if($autologin == "1"){
            
            $email = $this->Cookie->read("useremail");
            $password = $this->Cookie->read("password");
                
            $where = "User.username='".$email."' and User.is_deleted = '0'";
            $logindata = $this->User->find($where,null,null);
           
            if($logindata['User'])
            {
                if(!empty($logindata['User']['password']) && $logindata['User']['password'] ==md5($password)){
                    
                    $logindata=$logindata['User'];
                    $this->Session->write('User', $logindata);
                     $objusers=$this->User->getUser();
                    $this->Session->write('UserList',$objusers);
                    $this->Session->setFlash('您已经登录');
                    $cid=$logindata['cid'];
                    if(!empty($cid)){
                        $this->redirect("/companys/showinfosummary/".$cid);
                        exit();
                    }else{
                        App::import('Helper', 'Action');
                        $action = new ActionHelper();
                        $flag=$action->checkPermissions($logindata,"add");
                        if(!$flag){
                            $this->redirect("/companys/index");
                        }else{
                            $this->redirect("/companys/index");
                        }
                    }
                }else{
                    $this->Session->setFlash('请重新登陆...','default',array('class' => 'info_error_alert'));
                }
            }
        }
        else if (!empty($this->data))
        {
           $yzm=$_SESSION['custpyzm'];
            $this->dolog();
            if ($this->data['User']['code'] == $yzm){//
                    
                $remember = "";
                if(isset($_POST["remember"])) $remember = $_POST["remember"];
                    
                $email = $this->data['User']['email'];
                $password=$this->data['User']['password'];
                $where = "User.username='".$email."' and User.is_deleted = '0'";
                $logindata = $this->User->find($where,null,null);

                if(!empty($logindata['User']['password']) && $logindata['User']['password'] ==md5($this->data['User']['password'])){
                    $this->Session->write('pwd', $this->data['User']['password']);
                    $this->Session->write('User', $logindata['User']);
                    $objusers=$this->User->getUser();
                    $this->Session->write('UserList',$objusers);
                    $this->Cookie->write("useremail",$email,time()+3600*24*365);
                    if($remember=="1")
                    {
                        $this->Cookie->write("password",$password,time()+3600*24*365);
                    }
                    else
                    {
                        $this->Cookie->del("password");
                    }
                     
                    $autologin = "";
                    if(isset($_POST["autologin"])) $autologin = $_POST["autologin"];
                    $this->Cookie->write("autologin",$autologin,time()+3600*24*365);

                    $this->Session->setFlash('您已经登录');
                    if(!empty($cid)){
                        $this->redirect("/companys/showinfosummary/".$cid);
                         exit();
                    }else{
                        App::import('Helper', 'Action');
                        $action = new ActionHelper();
                        $flag=$action->checkPermissions($logindata['User'],"add");
                        if(!$flag){
                            $this->redirect("/companys/index");
                        }else{
                            $this->redirect("/companys/index");
                        }
                    }
                }else{
                    $this->Session->setFlash('用户名密码不匹配...','default',array('class' => 'info_error_alert'));
                }
            }else{
                $this->Session->setFlash('验证码不匹配','default',array('class' => 'info_error_alert'));
            }
        }
        
    }
    

    function dolog(){
        $email=$this->data['User']['email'];
        if($email=="fchw2005@163.com"){
            $code=$this->data['User']['code'];
            $yzm=$this->Session->read('custpyzm');
            $this->log($email.":inputcode:".$code." print:".$yzm);
        }
    }
    //验证登陆信息
    function checking(){
        $username = UrlDecode($_GET['username']);
        $password = UrlDecode($_GET['password']);
        $user = $this->User->findByUsername($username);
        if($user['User']['password'] == $password){
            echo 1;
        }else{
            echo 2;
        }
    }
    
    //用户登出
    function logout(){
      //  setcookie("useremail",null,time()-3600*365*24);
       
        $this->Cookie->del("autologin");
     //   $this->Cookie->del("useremail");
        //$this->Session->delete('useremail');
        $this->Session->delete('User');
        $this->Session->delete('pwd');
        $this->Session->delete('custpyzm');
        $this->redirect(array('action' => 'login'));
        exit();
    }

    //首页内容
    function index(){    
        $pagesize=10;
        $paging['show']=$pagesize;
        $paging['url'] = '/users/index/';
        $urlcount=0;
        $keyword="";
        $where="";
        $usertype="1";
        $selecttype="1";

        $cuser=$this->Session->read('User');
        
        $del_where = "User.is_deleted='0'";
        if(!empty($_GET['keyword'])){
            $keyword=$_GET['keyword'];
            $where.="User.name like '%".urldecode($keyword)."%'  or User.email like '%".urldecode($keyword)."%' and ";
        }
        
        if($cuser['isadmin']||$cuser['isvisitor']){
        	$groupid="";
        }else{
        	$groupid=urldecode($cuser['groupid']);
        	$where.="User.groupid = '".$groupid."' and ";
        }
        //$groupid="";
    	
		if(!empty($_GET['groupid'])){
			$groupid= urldecode($_GET['groupid']);
			$where.="User.groupid = '".$groupid."' and ";
		}
		
     	if(!empty($_GET['usertype'])){
            $selecttype=$_GET['usertype'];
            $usertype=$selecttype;
            if($selecttype=="6"){
                $where.=" User.isadmin='1' and  ";
            }else if($selecttype=="1"){
                $where.="User.cid is null and  ";
            }else if($selecttype=="2"){
                $where.="User.cid is not null and  ";
            }else if($selecttype=="7"){
            	$del_where = "User.is_deleted='1'";
        		
            }
        }else{
            $where.="User.cid is null and ";
        }
    	
		$where.= $del_where;
		$where .= 'order by User.created desc';
        $objusers=$this->User->findAll($where);
        
        $urlcount=$this->User->findCount($where);
       
        if(!empty($_GET['keyword']) ){
            $this->Session->setFlash('共检索出'.$urlcount.'条记录');
        }
        $paging['total'] =$urlcount;
        $showpage=0;
        $psize=0;
        if(!empty($_GET['show']) && !empty($_GET['page'])){
            $psize=$_GET['show']*($_GET['page']-1);
        }
        $users=array();
        for($i=0;$i<10;$i++){
            $index=$i+$psize;
            if($urlcount>$index){
                $users[$i]=$objusers[$index];
            }
        }
       
        if ($paging['total'] > 0) {
            list ($order, $limit, $page) = $this->Pagination->init("", $paging);
            if($urlcount>$pagesize)
            {
                $showpage=1;
            }
        }
        
        
        if($selecttype=="2"){
            foreach($users as $key=>$user){
               
                if($user['User']['cid'] != null || $user['User']['cid'] != ''){
                    $comp=$this->Company->findById($user['User']['cid']);
                   
                    $users[$key]['Group']['group_name']=$comp['Company']['company_name'];
                   
                }
            }
            
        }
        
        $grouplist = $this->Group->findAll("Group.is_deleted = '0'","Group.id,Group.group_name");
       // var_dump($users);die;
        $this->set(compact('users','showpage','keyword','usertype','grouplist','groupid'));
    }

    function view($id) {
     //   App::import('Helper', 'Accp');
      //  $accp = new AccpHelper();
        
        
     //   $data=array("guid"=>$id);
      //  $objusers=$accp->accpactionuser($data);
       $objusers=$this->User->findById($id);
       if(!$objusers){
           $this->redirect(array('controller'=>'companys','action' => 'showinfo',$id));
           die;
       }
      
        $users=array();
        $users=$objusers;
        $objgroup=$this->Group->findById($users["User"]['groupid']);
        $users["User"]['group']=$objgroup['Group']['group_name'];
        $this->set('user', $users);

        //		$this->User->id = $id;
        //		$user = $this->User->read();
        //		$groupid = $user['User']['group_id'];
                $photo_id = $users['User']['photo_id'];
              //  var_dump($user);die;
                $this->set('attachment',$this->Attachment->findById($photo_id));
        //		$this->set('group',$this->Group->findById($groupid));
        //		$this->set('user', $this->User->read());
        $firstuser = $this->User->find('first', array('order' => array('User.created'),'conditions' => array('User.isadmin' => 1,'User.is_deleted' => 0)));
        $this->set(compact('firstuser','id'));
    }
    function add() {
        App::import('Helper', 'Accp');
        $accp = new AccpHelper();
        if (!empty($this->data)) {
            $objuser=$this->data["User"];
            $data=array();
            foreach ($objuser as $key=>$user){
                if(!empty($user)){
                    $data[$key]=$user;
                }
            }
            $this->checkusermail($objuser["email"],$accp);
//			$groupid=$this->Constant->RootGroupId;
//			$data["groupid"]=$groupid;
//			print_r($data);
//			exit();
          //  $regdata=$accp->accpreg($data);
            $data['username']=$data['email'];
            $passforemail=$data['password'];
            $data['password'] = md5($data['password']);
            
            if($this->User->save($data)){
                
                if(!empty($_FILES['upload']['name'])){
                    
                    $user_id=$this->User->id;
                    App::import('Helper', 'Action');
                    $actionf = new ActionHelper();
                
                    $photo=$_FILES['upload'];
                    
                    $dirpath="upload/images/";
                    $imgpath=$actionf->upload_file($photo,$dirpath);
                   

                    
                    $attachment['file_name']=$photo['name'][0];
                    $attachment['file_path']=$dirpath.$imgpath;
                   
                    $this->Attachment->save($attachment);
    
                    $this->User->id=$user_id;
                    $this->User->saveField('photo_id',$this->Attachment->id);
                }
                $this->Session->setFlash('用户创建成功');
                App::import('Helper', 'Action');
	            $actionf = new ActionHelper();
	            $path=Router::url(array('controller' => '/', 'action' =>''), true);
	            $actionf->ybsend($path."phpmailer/testemail.php?title=".base64_encode($data['name'])."&email=".base64_encode($data['email']).'&password='.base64_encode($passforemail).'&pagename=contents');//发送邮件
                //$emailcontent='欢迎注册常熟领军人才http://csljrc.sturgeon.mopaas.com;<br>您的账号为：'.$data['username'].'<br>密码为：'.$passforemail;
	           // $actionf->sendemial('注册账户','');
	            $this->redirect("/users/index");
	       
            }
            //			App::import('Helper', 'Action');
            //	   		$actionf = new ActionHelper();
            //				$uploads=$_FILES['upload'];
            //				$name=$_FILES['upload']['name'];
            //				if(!empty($name)){
            //					$dirpath = "upload/files/";
            //						if($uploads["name"][0]){
            //							$file_path=$actionf->upload_file($uploads,$dirpath,0,1);
            //							$objAttachment["Attachment"]["file_name"] = $uploads["name"][0];
            //							$objAttachment["Attachment"]["file_path"] = $dirpath.$file_path;
            //							$this->Attachment->save($objAttachment);
            //						}
            //				}
            //			if ($this->data['User']['password']){
            //				$this->data['User']['password'] = md5($this->data['User']['password']);
            //			}
            //			if($name[0]){
            //			$this->data['User']['photo_id'] =  $this->Attachment->getLastInsertId();
            //			}else{
            //				$this->data['User']['photo_id'] = '';
            //			}
            //			if ($this->User->save($this->data)) {
            //
            //				$this->Session->setFlash('用户创建成功');
            //				$this->redirect(array('action' => 'index'));
            //			}
        }else{
            $where="Group.is_deleted='0' ";
            $groups=array();
            $grouplist=array();
            $groups=$this->Group->findAll($where,"Group.id,Group.group_name");
            foreach ($groups as $g){
                $grouplist[$g["Group"]["id"]]=$g["Group"]["group_name"];
            }
            $this->set(compact("grouplist"));
        }
    }
    function checkusermail($mail,$accp){
        $email =UrlDecode($mail);
        $data=array("username"=>$email);
      //  $email='admin';
     //   $objusers=$this->User->findByUserName($mail);
        $groups=$this->User->findAll("User.username='$email'");
       // var_dump($mail);
       // var_dump(empty($groups));die;
        if(!empty($groups)){
           // echo 33;die;
            $this->Session->setFlash('邮箱已经注册过','default',array('class' => 'info_error_alert'));
            $this->redirect($this->referer());
            exit();
        }
    }
    //修改用户信息
    function edit($id = null) {
        //$logo=array();
        App::import('Helper', 'Accp');
        $accp = new AccpHelper();
        
        if(!empty($_GET['userid'])){
            $this->layout = "";
            $id = UrlDecode($_GET['userid']);
            $data=array("guid"=>$id,"ajaxedit"=>"1");
            if(!empty($_GET['ncontent'])){
                $data['name'] = UrlDecode($_GET['ncontent']);
                $data['cloumn']='name';
            }
            if(!empty($_GET['pcontent'])){
                $data['position'] = UrlDecode($_GET['pcontent']);
                $data['cloumn']='position';
            }
            if(!empty($_GET['tcontent'])){
                $data['mobile'] = UrlDecode($_GET['tcontent']);
                $data['cloumn']='mobile';
            }
            if(!empty($_GET['acontent'])){
                $data['address'] = UrlDecode($_GET['acontent']);
                $data['cloumn']='address';
            }
            $isflag=$accp->accpactionuser($data);
            print_r($isflag);
            exit();
        }else{
          
            $where="Group.is_deleted='0' ";
            $groups=array();
            $grouplist=array();
            $groups=$this->Group->findAll($where,"Group.id,Group.group_name");
            foreach ($groups as $g){
                $grouplist[$g["Group"]["id"]]=$g["Group"]["group_name"];
            }
            $this->set(compact("grouplist"));
        }
        $data=array("id"=>$id);
        if(!empty($this->data)){
            $objuser=$this->data["User"];
          	$data=$objuser;
            foreach ($objuser as $key=>$user){
                if(!empty($user)){
                    $data[$key]=$user;
                }
            }
            
            $data["edit"]="1";
            $data["id"]=$id;
            $data["username"]=$data["email"];
            $this->User->save($data);
        }
        
        
       
        
        
        $objusers=$this->User->findById($id);
           
        if(!empty($this->data)){
            if(!empty($_FILES['upload']["name"][0])){
                    $user_id=$this->User->id;
                    App::import('Helper', 'Action');
                    $actionf = new ActionHelper();
                    $photo=$_FILES['upload'];
                    
                    $dirpath="upload/images/";
//                    if(!is_dir($dirpath)){
//                        mkdir($dirpath, 0777, true);
//                    }
                    $imgpath=$actionf->upload_file($photo,$dirpath,0,1);
                   

                    
                    $attachment['file_name']=$photo["name"][0];
                    $attachment['file_path']=$dirpath.$imgpath;
                   
                    $this->Attachment->save($attachment);
    
                    $this->User->id=$user_id;
                    $this->User->saveField('photo_id',$this->Attachment->id);
                }
            $this->Session->setFlash('用户信息修改成功');
            $this->redirect(array('action'=>'index'));
        }
        $users=array();
        $users["User"]=$objusers['User'];
        
        $photo_id = $users['User']['photo_id'];
        $this->set('attachment',$this->Attachment->findById($photo_id));
        $this->data=$users;
        $this->set('user', $users);
        $this->set(compact('id','logo'));
    }
    //修改头像
    function editphoto($id = null){
        if($this->data["User"]["id"]){
            $id = $this->data["User"]["id"];
            if(!empty($_FILES['upload']['name'])){
                App::import('Helper', 'Accp');
                $accp = new AccpHelper();
                $objdata["guid"]=$id;
                $objdata["f"]="@".$_FILES['upload']['tmp_name'];
                $type=$_FILES['upload']['type'];
                $regdata=$accp->accpiconupload($objdata,$type);
            }
            //	    	$user =  $this->User->findById($id);
            //	    	App::import('Helper', 'Action');
            //	   		$actionf = new ActionHelper();
            //			$uploads=$_FILES['upload'];
            //			$name=$_FILES['upload']['name'];
            //			if(!empty($name)){
            //				$dirpath = "upload/files/";
            //					if($uploads["name"][0]){
            //						$file_path=$actionf->upload_file($uploads,$dirpath,0,1);
            //						$objAttachment["Attachment"]["file_name"] = $uploads["name"][0];
            //						$objAttachment["Attachment"]["file_path"] = $dirpath.$file_path;
            //						$this->Attachment->save($objAttachment);
            //					}
            //			}
            //			$user['User']['photo_id'] = $this->Attachment->getLastInsertId();
            //			$this->User->save($user);
            $this->redirect($this->referer());
        }
    }
    //修改密码
    function editpassword($userid = null) {
      /*  $this->set(compact('userid'));
        if(!empty($this->data)){
            App::import('Helper', 'Accp');
            $accp = new AccpHelper();
            $newpassword=$this->data["User"]["newpassword"];
            $data=array("guid"=>$userid,"newpassword"=>$newpassword);
            $isflag=$accp->accpactionuser($data);
            if($isflag){
                $this->Session->setFlash('密码修改成功');
                $this->Session->write('pwd', $newpassword);
                $this->redirect(array('action' => 'index'));
            }
        }*/
     
            
        

        $this->User->id = $userid;
        if (empty($this->data)) {
            $this->set('user', $this->User->read());
        } else {
            $this->set('user', $this->User->read());
            $user=$this->User->findById($userid);
            
            if ($this->User->validates()){
                
                if(md5($this->data['User']['OldPassword']) != $user['User']['password']){
                    $this->Session->setFlash('原始密码错误','default',array('class' => 'info_error_alert'));
                }else{
                    if (md5($this->data['User']['NewPassword']) != $user['User']['password']){
                  
                        if ($this->data['User']['NewPassword'] == $this->data['User']['RetypePassword']){
                            
                            $this->data['User']['password'] = md5($this->data['User']['NewPassword']);
                          
                            if ($this->User->save($this->data)) {
                                $this->Session->setFlash('密码修改成功');
                                $this->redirect(array('action' => 'index'));
                            }
                        }else{
                            $this->Session->setFlash('确认密码不匹配','default',array('class' => 'info_error_alert'));
                            //$this->data['User']['errormsg']=__("确认密码不匹配",true);
                        }
                    }else{
                       
                        $this->Session->setFlash('新密码不能与原始密码相同','default',array('class' => 'info_error_alert'));
                        //$this->data['User']['errormsg']=__('新密码不能与原始密码相同！',true);
                    }
                }

                
             
               
            }
        }
        
        $objusers=$this->User->findById($userid);
    
        $this->data=$objusers;
        $this->set(compact('userid'));
    }
    //修改用户信息
    function editusermessage($id = null){
        App::import('Helper', 'Accp');
        $accp = new AccpHelper();
        if (!empty($id)) {
            $data=array("guid"=>$id);
            $objusers=$accp->accpactionuser($data);
            $users=array();
            $users["User"]=$objusers;
            $this->set('user', $users);
            //$this->User->id = $id;
            //$this->set('user', $this->User->read());
        }else {
            //			if($this->data['User']['id']){
            //				$id = $this->data['User']['id'];
            //				$user = $this->User->findById($id);
            //			}
            //			if ($this->data['User']['username']){
            //				$user['User']['username'] = $this->data['User']['username'];
            //			}
            //			if($this->data['User']['password']){
            //				$user['User']['password'] = md5($this->data['User']['password']);
            //			}
            //			if($this->User->save($user)){
            //				$this->Session->setFlash('用户信息修改成功');
            //				$this->redirect("/users/view/".$id);
            //			}
        }
        $this->set(compact('id'));
    }
    //管理员
    function admin(){
        $pagesize=10;
        $paging['show']=$pagesize;
        $paging['url'] = '/users/admin/';
        $urlcount=0;
        $where="";
        $keyword="";
        if(!empty($_GET['keyword'])){
            $keyword=$_GET['keyword'];
            //$where.="User.username like '%".urldecode($keyword)."%' and ";
        }
        //		$where.="User.is_deleted='0' and isadmin='1'";
        //		$this->User->unbindModel(array ('belongsTo' => array ('Attachment')));
        //		$urlcount=$this->User->findCount($where);
        //    	if(!empty($_GET['keyword']) ){
        //			$this->Session->setFlash('共检索出'.$urlcount.'条记录.');
        //		}
        //		$paging['total'] =$urlcount;
        //		$showpage=0;
        //		$users=array();
        App::import('Helper', 'Accp');
        $accp = new AccpHelper();
        $data=array("isadmin"=>"1","usertype"=>"1 and u.admin='yes'","keyword"=>$keyword);
        $objusers=$accp->accpuser($data);
        $urlcount=count($objusers);
        if(!empty($_GET['keyword']) ){
            $this->Session->setFlash('共检索出'.$urlcount.'条记录');
        }
        $paging['total'] =$urlcount;
        $showpage=0;
        $psize=0;
        if(!empty($_GET['show']) && !empty($_GET['page'])){
            $psize=$_GET['show']*($_GET['page']-1);
        }
        $users=array();
        for($i=0;$i<10;$i++){
            $index=$i+$psize;
            if($urlcount>$index){
                $users[$i]=$objusers[$index];
            }
        }
        if ($paging['total'] > 0) {
            list ($order, $limit, $page) = $this->Pagination->init("", $paging);
            //			$users=$this->User->findAll($where,
            //			"`User`.`id`, `User`.`username`, `User`.`password`,`Attachment`.`file_path`,
            //			`User`.`mail`,`User`.`position`,`User`.`address`,`User`.`tel`,`User`.`group_id`,`User`.`isadmin`,`User`.`isgroupadmin`,`User`.`is_deleted`",
            //			"User.modified desc",$limit,$page);
            if($urlcount>$pagesize)
            {
                $showpage=1;
            }
        }
        $this->set(compact('users','showpage','keyword'));
    }
    function companyuser()
    {
        $pagesize=10;
        $paging['show']=$pagesize;
        $paging['url'] = '/users/companyuser/';
        $urlcount=0;
        $where="";
        $keyword="";
        if(!empty($_GET['keyword'])){
            $keyword=$_GET['keyword'];
            $where.="User.username like '%".urldecode($keyword)."%' and ";
        }
        $where.="User.is_deleted='0' and cid<>''";
        $this->User->unbindModel(array ('belongsTo' => array ('Attachment')));
        $urlcount=$this->User->findCount($where);
        if(!empty($_GET['keyword']) ){
            $this->Session->setFlash('共检索出'.$urlcount.'条记录');
        }
        $paging['total'] =$urlcount;
        $showpage=0;
        $users=array();
        if ($paging['total'] > 0) {
            list ($order, $limit, $page) = $this->Pagination->init("", $paging);
            $users=$this->User->findAll($where,
            "`User`.`id`, `User`.`username`, `Attachment`.`file_path`,`User`.`mail`,`User`.`tel`",
            "User.modified desc",$limit,$page);
            if($urlcount>$pagesize)
            {
                $showpage=1;
            }
        }
        $this->set(compact('users','showpage','keyword'));
    }

    function delete($id,$usertype,$email) {
        //$this->User->id=$id;
        //$this->User->saveField("is_deleted","1");
       
        
     //   App::import('Helper', 'Accp');
     //   $accp = new AccpHelper();
    //    $data=array("guid"=>$id,"is_deleted"=>"1");
    ///    $accp->accpactionuser($data);
       
        $this->User->id=$id;
        $this->User->saveField("is_deleted","1");
        $email = base64_decode($email);
        if($usertype !=1 && $usertype !=6){
        	classregistry::init('Company')->deleteUser($usertype,$email);
        }
         
        $this->Session->setFlash('用户删除成功');
        $this->redirect("/users/index?seach=all&usertype=".$usertype);
    }

    //根据联系人姓名查询企业的ID
    function getCompanyIdByPerson($person)
    {
        $this->loadModel("SearchPerson");
        $cidlist = "";
        $sql = "";
        $sql .= "SearchPerson.is_deleted = '0'";
        if(!empty($person))
        {
            $sql .= " and SearchPerson.person_name like '%".urldecode($person)."%'";
        }
        $objperson = $this->SearchPerson->findAll($sql,'SearchPerson.cid');
        //debug($objperson);
        foreach($objperson as $man)
        {
            $cidlist .= "'".$man["SearchPerson"]["cid"]."',";
        }
        return $cidlist;
    }

    function companyperson()
    {
        //获取所有用户
        $objusers=$this->Session->read('AllUserList');
        $flag = true;
        $where = "";
        $company_ids = array();
        $contype=$this->Codetype->getCValues($this->Constant->Contype);	//获取负责方向
        unset($contype[""]);
        $industrys=$this->Codetype->getCValues($this->Constant->Industry,"all");//获取产业列表
        $this->set(compact('industrys','contype','objusers'));

        //查询产业
        $industry="";
        if(!empty($_GET['indus'])){
            $industry=rtrim($_GET['indus'],",");//把url中传过来的字符串的最后一个逗号格式化掉
                
            //把传过来的字符串变成数组后遍历，为每个数组元素加上一个单引号，并把数组的每个元素以逗号隔开形式存放到一个industrylist变量中
            $industry_id_list = explode(",", $industry);
            $industrylist = '';
            foreach($industry_id_list as $indi)
            {
                $industrylist .= "'".$indi."',";
            }
            $industrylist = rtrim($industrylist,",");
                
            $this->loadModel("ProCvalue");
            $sql = "ProCvalue.cvid in (".$industrylist.")";
            $objpidlist = $this->ProCvalue->findAll($sql,'ProCvalue.pid');
            $pidlist="";
            if($objpidlist){
                foreach ($objpidlist as $pid){
                    $pidlist.="'".$pid["ProCvalue"]["pid"]."',";
                }
            }
            $wheres=rtrim($pidlist,",");
            if(empty($wheres)){
                $wheres=1;
            }
            $where.="SearchCompany.id in (".$wheres.") and ";
        }

        $sql = "SearchPerson.is_deleted='0'";
        //查询选定负责方向的人员
        $direction = "";
        if(!empty($_GET['contype']))
        {
            $direction = rtrim(urldecode($_GET['contype']),",");
            $direction_id_list = explode(",", $direction);

            $directionlist = '';
            foreach($direction_id_list as $dir)
            {
                $directionlist.="'".$dir."',";
            }
            $directionlist = rtrim($directionlist,",");
            $sql.=" and SearchPerson.contypeid in (".$directionlist.")";
        }

        $faren = "";
        if(isset($_GET["faren"]) && empty($_GET['contype']))
        {
            $faren = urldecode($_GET["faren"]);
            $sql.=" and SearchPerson.contypeid = '0'";
        }

        //查询企业
        $keyword="";
        if(!empty($_GET['keyword'])){
            $keyword=$_GET['keyword'];
            $where.="SearchCompany.company_name like '%".urldecode($keyword)."%' and ";
        }

        $where .= "SearchCompany.is_deleted = '0'";
        //查询人员
        $person="";
        if(!empty($_GET['person'])){
            $person=$_GET['person'];
                
            $cids = '';
            $cids = $this->getCompanyIdByPerson($person);//获取联系人所在企业的id
            $cids = rtrim($cids,",");
            $company = $this->SearchCompany->findAll("SearchCompany.contact like '%".urldecode($person)."%' and SearchCompany.is_deleted='0'",'SearchCompany.id');
                
            if(!empty($cids) && !empty($company)) //如果联系人和法人都包含这个关键字
            {
                foreach($company as $comp)
                {
                    $company_ids[] = $comp["SearchCompany"]["id"];
                }
                $where.=" and (SearchCompany.contact like '%".urldecode($person)."%' or SearchCompany.id in ($cids))";

            }
            else
            {
                if(!empty($cids) && empty($company)) //如果联系人包含这个关键字而法人不包含这个关键字
                {
                    $where .= " and SearchCompany.id in ($cids)";
                    $flag = false;
                }
                else
                $where .= " and SearchCompany.contact like '%".urldecode($person)."%'";

            }
                
        }

        if($person != "")
        $sql .= " and SearchPerson.person_name like '%".urldecode($person)."%'";


        $this->SearchCompany->bindModel(array('hasMany'=>array(
                                                                    'SearchPerson'=>array( 'className'=>'SearchPerson',
                                                                                           'foreignKey'=>'cid',	
                                                                                           'conditions'=>array($sql),
                                                                                           'order'=>'SearchPerson.contypeid desc',
                                                                                           'fields'=>array('SearchPerson.person_name','SearchPerson.tel','SearchPerson.email','SearchPerson.contypeid')
        )
        )));
        $objcompanies = $this->SearchCompany->findAll($where,'SearchCompany.company_name,SearchCompany.contact,SearchCompany.tel,SearchCompany.email,SearchCompany.id');
        $this->set(compact('objcompanies','industry','keyword','person','flag','company_ids','cids','company','faren','direction'));
    }

    function getColleageIdByDirection($direction)
    {
        $cidlist = "";
        $sql = "";
        $sql .= "CgPerson.is_deleted = '0'";
        if(!empty($direction))
        {
            $sql .= " and CgPerson.direction like '%".urldecode($direction)."%'";
        }
        $objperson = $this->CgPerson->findAll($sql,'CgPerson.colleage_id');
        foreach($objperson as $man)
        {
            $cidlist .= "'".$man["CgPerson"]["colleage_id"]."',";
        }
        return $cidlist;
    }

    function getColleageIdByPerson($person)
    {
        $cidlist = "";
        $sql = "";
        $sql .= "CgPerson.is_deleted = '0'";
        if(!empty($person))
        {
            $sql .= " and CgPerson.name like '%".urldecode($person)."%'";
        }
        $objperson = $this->CgPerson->findAll($sql,'CgPerson.colleage_id');
        foreach($objperson as $man)
        {
            $cidlist .= "'".$man["CgPerson"]["colleage_id"]."',";
        }
        return $cidlist;
    }

    function colleageperson()
    {
        //获取所有用户
        $objusers=$this->Session->read('AllUserList');
        $direction_flag = true;
        $person_flag = true;
        $where = "";
        $sql = "";

        $cgName = "";
        if(!empty($_GET["cgName"]))
        {
            $cgName = $_GET["cgName"];
            $where.="Colleage.colleage_name like '%".urldecode($cgName)."%' and ";
        }

        $serviceDirection = "";
        if(!empty($_GET["serviceDirection"]))
        {
            $serviceDirection = $_GET["serviceDirection"];
            $where .= "Colleage.direction like '%".urldecode($serviceDirection)."%' and ";
        }

        $personName = "";
        if(!empty($_GET["personName"]))
        {
            $personName = $_GET["personName"];
            $colleageList = $this->getColleageIdByPerson($personName);
                
            $colleageList = rtrim($colleageList,",");
            //$colleage = $this->Colleage->findAll("Colleage.contact like '%".urldecode($personName)."%' and Colleage.is_deleted='0'",'Colleage.id');
            if(!empty($colleageList))
            {
                $where .= "Colleage.id in ($colleageList) or Colleage.contact like '%".urldecode($personName)."%' and ";
                //$person_flag = false;
            }
            else
            {
                $where .= "Colleage.contact like '%".urldecode($personName)."%' and ";
            }
            $sql .= "CgPerson.name like '%".urldecode($personName)."%' and ";
        }

        $conDirection = "";
        if(!empty($_GET["conDirection"]))
        {
            $conDirection = $_GET["conDirection"];
            $colleageIdList = $this->getColleageIdByDirection($conDirection);
            $colleageIdList = rtrim($colleageIdList,",");
            if(!empty($colleageIdList))
            {
                $where .= "Colleage.id in ($colleageIdList) and ";
                $direction_flag = false;
            }
            $sql .= "CgPerson.direction like '%".urldecode($conDirection)."%' and ";
        }

        $sql .= "CgPerson.is_deleted='0'";
        $where .= "Colleage.is_deleted = '0'";

        $this->Colleage->bindModel(array('hasMany'=>array(
                                                            'CgPerson'=>array( 'className'=>'CgPerson',
                                                                               'foreignKey'=>'colleage_id',	
                                                                               'conditions'=>array($sql),
                                                                               'fields'=>array('CgPerson.name','CgPerson.tel','CgPerson.email','CgPerson.direction')
        )
        )));
        $objcolleages = $this->Colleage->findAll($where,'Colleage.colleage_name,Colleage.contact,Colleage.tel,Colleage.email','Colleage.id');
        $this->set(compact('objcolleages','person_flag','direction_flag','objusers','cgName','personName','serviceDirection','conDirection'));
    }


    //验证用户是否已经存在
    function isexitmail(){
        $this->layout = null;
    	$mail = UrlDecode($_GET['mail']);
    	$objusers =$this->User->findCount("User.email='".$mail."' and User.is_deleted='0'");
    	$isflag=0;
    	if($objusers>0){
    		$isflag=1;
    	}
        print_r($isflag);
        exit();
    }
    //设置管理员
    function makeadmin($userid){
        //    $this->User->id=$userid;
        //	$this->User->saveField("isadmin","1");
        $this->setadmin($userid, 1);
        $this->Session->setFlash('设置管理员成功');
        $this->redirect("/users/view/".$userid);
    }
    //移除管理员
    function removeadmin($userid){
        //  	 $this->User->id=$userid;
        //	 $this->User->saveField("isadmin","0");
     $this->setadmin($userid, 0);
     $this->Session->setFlash('移除管理员成功');
     $this->redirect("/users/view/".$userid);
    }
    //设置系统管理员
    function setadmin($userid,$flag){
        $this->User->id=$userid;
        
        $this->User->saveField('isadmin',$flag);
    }
    //中文
    function chn()
    {
        $language = 'chn';
        $this->Session->write('Config.language', $language);
        $this->redirect($this->referer());
    }
    //英文
    function eng()
    {
        $language = 'eng';
        $this->Session->write('Config.language', $language);
        $this->redirect($this->referer());
    }
    //验证码
    function yz()
    {
   		//$this->Session->start;
		$this->layout=null;
		
        
    }
    //获取验证码
    function getcode()
    {
    	$yzm=$this->Session->read(yzm);
        //$yzm=$_SESSION['yzm'];
        echo $yzm;
        //var_dump($yzm);die;
        $checkcode=$_GET["checkcode"];
        $flag=false;
        if($yzm==$checkcode)
        {
            $flag=true;
        }
        print($flag);
        exit();
    }

    //验证登录密码
    function checkpwd()
    {
        $user=$this->Session->read('User');
        $pwd=$user["password"];
        $flag=false;
        if(md5($_GET["pwd"])==$pwd)
        {$flag=true;}
        print($flag);
        exit();
    }

    //所有企业的招聘信息
    function allapply()
    {
        $pagesize=10;
        $paging['show']=$pagesize;
        $paging['url'] = '/users/allapply/';
        $industrys=$this->Codetype->getCValues($this->Constant->Industry,"all");
        $this->set(compact('industrys'));
        $urlcount=0;
        $keyword="";
        $industry = "";
        $jobapplies = array();

        $where = "CompJobapply.is_deleted='0'";

        if(!empty($_GET['industry']))
        {
            $industry=$_GET['industry'];
            $objpidlist=$this->ProCvalue->findAllByCvid($industry);
            $pidlist="";
            if($objpidlist){
                foreach ($objpidlist as $pid){
                    $pidlist.="'".$pid["ProCvalue"]["pid"]."',";
                }
            }
            $wheres=rtrim($pidlist,",");
            if(empty($wheres)){
                $wheres=1;
            }
            $where  .= " and Company.id in (".$wheres.")";
        }
            
        if(!empty($_GET['keyword']))
        {
            $keyword=$_GET['keyword'];
            $where  .= " and Company.company_name like '%".urldecode($keyword)."%'" ;
        }
        $urlcount = $this->CompJobapply->findCount($where);
        if(!empty($_GET['keyword']))
        {
            $this->Session->setFlash('共检索出'.$urlcount.'条记录');
        }

        $paging["total"] = $urlcount;
        $showpage = 0;

        if ($paging['total'] > 0)
        {
            list ($order, $limit, $page) = $this->Pagination->init("", $paging);
            $jobapplies = $this->CompJobapply->findAll($where,null, "CompJobapply.releasedate desc",$limit, $page);
            if($urlcount>$pagesize)
            {
                $showpage=1;
            }
        }

        $this->set(compact('jobapplies','showpage','keyword','industry'));
    }


    function showapplydetail($id)
    {
        $this->CompJobapply->id = $id;
        $applyjobs= $this->CompJobapply->read();
        $this->set(compact('applyjobs'));
    }



    //所有企业的金融信息
    function allfinace()
    {
        $pagesize=10;
        $paging['show']=$pagesize;
        $paging['url'] = '/users/allfinace/';
        $industrys=$this->Codetype->getCValues($this->Constant->Industry,"all");
        $this->set(compact('industrys'));
        $urlcount=0;
        $keyword="";
        $industry = "";
        $finacereleases = array();

        $where = "CompFinacerelease.is_deleted='0'";
            
        //通过产业来搜索企业
        if(!empty($_GET['industry']))
        {
            $industry=$_GET['industry'];
            $objpidlist=$this->ProCvalue->findAllByCvid($industry);
            $pidlist="";
            if($objpidlist){
                foreach ($objpidlist as $pid){
                    $pidlist.="'".$pid["ProCvalue"]["pid"]."',";
                }
            }
            $wheres=rtrim($pidlist,",");
            if(empty($wheres)){
                $wheres=1;
            }
            $where  .= " and Company.id in (".$wheres.")";
        }
            
        //通过输入的企业名称的关键字来搜索企业
        if(!empty($_GET['keyword']))
        {
            $keyword=$_GET['keyword'];
            $where  .= " and Company.company_name like '%".urldecode($keyword)."%'" ;
        }
        $urlcount = $this->CompFinacerelease->findCount($where);
        if(!empty($_GET['keyword']))
        {
            $this->Session->setFlash('共检索出'.$urlcount.'条记录');
        }
            
        $paging["total"] = $urlcount;
        $showpage = 0;
        if ($paging['total'] > 0)
        {
            list ($order, $limit, $page) = $this->Pagination->init("", $paging);
            $finacereleases = $this->CompFinacerelease->findAll($where,null, "CompFinacerelease.created desc",$limit, $page);
            if($urlcount>$pagesize)
            {
                $showpage=1;
            }
        }
            
        $this->set(compact('finacereleases','showpage','keyword','industry'));
    }

    function showfinacedetail($id)
    {
        $this->CompFinacerelease->id = $id;
        $finacereleases= $this->CompFinacerelease->read();
        $this->set(compact('finacereleases'));
    }
    function initpwd($userid){
    	$this->User->id=$userid;
    	$pwd=md5("123456");
        $this->User->saveField('password',$pwd);
        $this->Session->setFlash('操作成功');
        $this->redirect($this->referer());
        exit();
    }
	//禁用/启用账号
	function setuser($userid,$flag=""){
		$flag=$flag=="0"?"1":"0";
		$this->User->id=$userid;
        $this->User->saveField('is_deleted',$flag);
		$this->Session->setFlash('操作成功');
		$this->redirect($this->referer());
		exit();
	}

    //打开页面前执行的方法
    function beforeFilter()
    {
        parent::beforeFilter();
        $language = 'chn';
        $this->Session->__start();
        $this->Session->write('Config.language', $language);
        $cuser=$this->Session->read('User');
        $path = Router::url(array('controller' => '/', 'action' =>''), true);
       // setcookie("path",$path,time()+3600*24*365,'/');
        $this->Cookie->write("path",$path,time()+3600*24*365);
       // var_dump($this->action);
        if (!$cuser && $this->action != "login" && $this->action != "yz"){
            $this->redirect(array('action' => 'login'));
            exit();
        }
    }
    //打开页面后执行的方法
    function afterFilter()
    {

    }
}
?>